<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.value" clearable placeholder="输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select v-model="query.type" clearable placeholder="类型" class="filter-item" style="width: 130px">
          <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-form-item label="上传图片">
            <el-upload style="margin-left:50%;transform:translateX(-74px)"
                       action="#"
                       :http-request="uploadImg"
                       :show-file-list="false"
                       :on-change="changeHande"
                       :before-remove="remove"
                       :auto-upload="true">
              <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="模版名称">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="文案一">
            <el-input v-model="form.clerkOne" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="文案二">
            <el-input v-model="form.clerkTwo" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns.visible('id')" prop="id" label="id" />
        <el-table-column v-if="columns.visible('name')" prop="name" label="模版名称" />

        <el-table-column v-if="columns.visible('imgUrl')" prop="imgUrl" label="海报" >
          <template slot-scope="scope">
<!--            {{scope.row.imgUrl}}-->
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.imgUrl"
              :preview-src-list="[scope.row.imgUrl]">
            </el-image>
          </template>
        </el-table-column>


        <el-table-column v-if="columns.visible('clerkOne')" prop="clerkOne" label="文案一" />
        <el-table-column v-if="columns.visible('clerkTwo')" prop="clerkTwo" label="文案二" />
        <el-table-column v-if="columns.visible('createTime')" prop="createTime" label="创建时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','telImage:edit','telImage:del']" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudTelImage from '@/api/telImage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import MaterialList from "@/components/material";
import COS from 'cos-js-sdk-v5'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '图片管理', url: 'api/telImage', sort: 'id,desc', crudMethod: { ...crudTelImage }})
const defaultForm = { id: null, name: null, imgUrl: null, clerkOne: null, clerkTwo: null, createTime: null }
export default {
  name: 'TelImage',
  components: { pagination, crudOperation, rrOperation, udOperation ,MaterialList},
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      dialogVisible: false,
      // 图片文件
      imgFile: '',
      // 图片文件名称
      fileName: '',
      // 上传成功后的地址
      imgURL: '',
      permission: {
        add: ['admin', 'telImage:add'],
        edit: ['admin', 'telImage:edit'],
        del: ['admin', 'telImage:del']
      },
      rules: {
      },
      queryTypeOptions: [
        { key: 'name', display_name: '模版名称' }
      ]
    }
  },
  watch: {
  },
  methods: {
    remove(info){
      console.log('info',info)
      let data = {
        ...this.form,
        imgUrl:''
      }
      this.$set(this,'form',data)
    },
    changeHande (file, fileList) {
      console.log('33333')

      console.log(file)
      this.imgFile = file
      this.fileName = file.name
      // 上传之后将上传封面隐藏，避免频繁操作
      const upload = document.getElementById('text')
      // const parent = upload.parentNode
      // parent.style.display = 'none'
    },
    async uploadImg () {
      // 创建COS实例  获取签名
      console.log('33333')
      var cos = new COS({
        SecretId: 'AKIDRhhRu63j8G8j36uRhgPs4zd06vTlmWzB', //密钥id
        SecretKey: 'xd3E9nBI9l7D2arqZ2E9nBH6evve6HCq' //密钥的key
      });
      console.log('this.imgFile',this.imgFile)
      cos.putObject({
        Bucket: 'images-1301967145', // 桶名-APPID  必须
        Region: 'ap-guangzhou', //区域 必须
        Key: this.GetTimeString() + '.jpg', //文件名必须
        StorageClass: 'STANDARD',
        Body: this.imgFile.raw, // 上传文件对象
        onProgress: (res) => {
          let num = parseInt(res.loaded / res.total * 100)
        }
      }, (err, res) => {
        console.log('err, res',err, res)
        if(err){
          this.$notify.error('上传失败')
          return
        }
        if (res.statusCode && res.statusCode == '200') {
          this.$notify.success('上传成功')
          let url = `http://${res.Location}`
          this.form.imgUrl = url
          console.log('this.from',this.form)
        } else {
          this.$notify.error('上传失败')
        }
      });
    },
    GetTimeString() {
      var date = new Date();
      var yy = date.getFullYear().toString();
      var mm = (date.getMonth() + 1).toString();
      var dd = date.getDate().toString();
      var hh = date.getHours().toString();
      var nn = date.getMinutes().toString();
      var ss = date.getSeconds().toString();
      var mi = date.getMilliseconds().toString();
      var ret = yy + mm + dd + hh + nn + ss + mi;
      return ret;
    },
    uploadFile(){
      var cos = new COS({
        SecretId: 'AKIDRhhRu63j8G8j36uRhgPs4zd06vTlmWzB', //密钥id
        SecretKey: 'xd3E9nBI9l7D2arqZ2E9nBH6evve6HCq' //密钥的key
      });
      cos.putObject({
        Bucket: 'images-1301967145', // 桶名-APPID  必须
        Region: 'ap-guangzhou', //区域 必须
        Key: this.GetTimeString() + '.jpg', //文件名必须
        StorageClass: 'STANDARD',
        Body: tempFiles[0], // 上传文件对象
        onProgress: (res) => {
          let num = parseInt(res.loaded / res.total * 100)
        }
      }, (err, res) => {
        if(err){
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          return
        }
        if (res.statusCode && res.statusCode == '200') {
          uni.showToast({
            title: '上传成功'
          })
          let mydata = {
            ...this.data,
            picture: `http://${res.Location}`
          }
          this.$set(this, 'data', mydata)
        } else {
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      });
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }else{
        delete this.crud.params.name
      }
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
  }
}



</script>

<style >
  .avatar-uploader .el-upload {
    border: 1px dashed #999;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    border: 1px dashed #999;
    display: block;
  }
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
</style>
